import {computed, reactive, ref, toRefs, watch} from "vue";
import {useStore} from "vuex";
import {loginService} from "./login";
import {BugFeedVo, Dept, Feed, LocalChange, Room} from "../sql/domin";
import {FeedMapper} from "../mappers/FeedMapper";
import {LocalChangeMapper} from "../mappers/LocalChangeMapper";
import {ChangeStatus, ChangeType, TargetType} from "../util/Constants";
import {onLoad} from "@dcloudio/uni-app";
import {parseTime} from "../util/auth";
import {refreshAuditBzz, refreshAuditHead, syncAuditBzz, syncAuditHead} from "../api/audit";
import {AuditToFeed} from "../util/objectUtils";
import {DeptMapper} from "../mappers/DeptMapper";
import {RoomMapper} from "../mappers/RoomMapper";

export function AuditDataHandle() {

    const store = useStore()

    const userId = store.getters.userId

    const deptId = store.getters.deptId

    const role = store.getters.role

    const type = role == 'head' ? 'Head' : role == 'bzz' ? 'Bzz' : 'Feed'

    const refreshAudits = async () => {
        let feeds : Feed[] = []
		FeedMapper.deleteAudit(type)
        if (type == 'Head'){
            feeds = (await refreshAuditHead()).data.data as Feed[]
        }
        if (type == 'Bzz') {
            feeds = (await refreshAuditBzz()).data.data as Feed[]
        }
        let locals = (await FeedMapper.selectFeedList(deptId,type)) as Feed[]
		console.log(feeds);
        let changes = (await LocalChangeMapper.selectLocalChangeList(deptId,role == 'head'?TargetType.HEAD:TargetType.BZZ)) as LocalChange[]
		if(feeds.length != 0){
			feeds.forEach(it=>{
            it = AuditToFeed(it)
            //如果本地已变更 则跳过更新
            if (changes.findIndex((val)=>val.targetId == it.id+'') != -1){
                return
            }
            // 如果本地已存在，则更新
            if (locals.findIndex((val)=>val.id == it.id) != -1){
                FeedMapper.updateFeedById(it,type)
                return;
            }
            it.tableType = type
            //本地不存在则新增
            FeedMapper.InsertFeed(it)
			})
		}
        
    }

    const syncAudits = async () : Promise<number> => {
        let locals = (await FeedMapper.selectFeedList(deptId,type)) as Feed[]
        let changes = (await LocalChangeMapper.selectLocalChangeList(userId,role == 'head'?TargetType.HEAD:TargetType.BZZ)) as LocalChange[]
        let ups : Feed[] = []
        changes.forEach(it=>{
            let index = locals.findIndex((val)=>val.id+'' == it.targetId)
            if (index != -1){
                ups.push(locals[index])
            }
        })
        if (ups.length != 0){
            let result:LocalChange[] = []
            if (type == 'Head'){
                result = (await syncAuditHead(ups)).data.data as LocalChange[]
            }
            if (type == 'Bzz'){
                result = (await syncAuditBzz(ups)).data.data as LocalChange[]
            }
            for (let it of result){
				await FeedMapper.deleteFeedById(Number.parseInt(it.targetId as string))
                await LocalChangeMapper.deleteLocalChangeByTargetId(it.targetId as string,role)
            }
            return result.length
        }
        return 0
    }

    const getList = async () => {
        let feeds: Feed[] = []
        let changes: LocalChange[] = []
        if (role == 'head') {
            feeds = await FeedMapper.selectFeedList(deptId, 'Head') as Feed[]
            changes = await LocalChangeMapper.selectLocalChangeList(userId, TargetType.HEAD) as LocalChange[]
        }
        if (role == 'bzz') {
            feeds = await FeedMapper.selectFeedList(deptId, 'Bzz') as Feed[]
            changes = await LocalChangeMapper.selectLocalChangeList(userId, TargetType.BZZ) as LocalChange[]
        }
        console.log(feeds); 
        //(changes)
        return feeds.map(it => {
            return {
                feed: it,
                change: changes.filter(i => i.targetId == it.id)[0]
            } as BugFeedVo
        })
    }

    return {
        refreshAudits,
        syncAudits,
        getList
    }
}

export function AuditClickHandle() {

    const content = reactive([
        {
            iconPath: '/static/refrash.png',
            selectedIconPath: '/static/refrash-active.png',
            text: '刷新',
            active: false
        },
        {
            iconPath: '/static/upload.png',
            selectedIconPath: '/static/upload-active.png',
            text: '同步',
            active: false
        }
    ])

    const selectIndex = ref(0)

    const currentIndex = ref(1)

    const {getNetWorkType} = loginService()

    const {refreshAudits, syncAudits, getList} = AuditDataHandle()

    const feeds = ref<Array<BugFeedVo>>()

    const handleClick = async (e: any) => {
        selectIndex.value = e.index
        switch (e.index) {
            case 0:
                uni.showToast({
                    icon: 'none',
                    title: '正在检查网络'
                })
                if (await getNetWorkType()) {
                    uni.showLoading({
                        title: '网络连接成功,正在拉取数据'
                    })
                    await refreshAudits()
                    feeds.value = await getList()
                    uni.hideLoading()
                }
                break
            case 1:
                uni.showToast({
                    icon: 'none',
                    title: '正在检查网络'
                })
                if (await getNetWorkType()) {
                    uni.showLoading({
                        title: '网络连接成功,正在拉取数据'
                    })
                    await syncAudits()
                    feeds.value = await getList()
                    uni.hideLoading()
                }
                break
        }
    }

    const handleChange = (index: number) => {
        currentIndex.value = index
    }

    watch(selectIndex, (newVal, oldVal) => {
        content[newVal].active = true
        content[oldVal].active = false
    })

    const handleUpdate = (id: number) => {
        uni.navigateTo({url: '/pages/audit/form?id=' + id})
    }

    const feedList = computed(() => {
        return feeds.value?.filter(it => {
            if (currentIndex.value == 0)
                return true
            if (currentIndex.value == 1)
                if (it.change == null && it.feed.tableStatus == '1') {
                    return true
                }
            if (currentIndex.value == 2)
                if (it.feed.tableStatus == '2') {
                    return true
                }
            if (currentIndex.value == 3)
                if (it.feed.tableStatus == '0') {
                    return true
                }
        })
    })

    onLoad(async ()=>{
        feeds.value = await getList()
    })

    return {
        content,
        handleClick,
        handleChange,
        currentIndex,
        handleUpdate,
        getList,
        feedList
    }
}

export function AuditFormHandle() {


    const data = reactive({
        feed:{}as Feed
    })

    const {feed} = toRefs(data)

    const store = useStore()

    const title = ref('')

    const isShow = ref()

    const role = store.getters.role

    const remark = ref('')

    const tableStatus = ref()

    let targetType: TargetType = TargetType.HEAD

    const roomList = ref<Room[]>([])

    const deptList = ref<Dept[]>()

    onLoad(async (prop) => {
        if (prop.id != null) {
            if (role == 'head') {
                data.feed = (await FeedMapper.selectFeedById(Number.parseInt(prop.id), 'Head') as Feed[])[0]
            }
            if (role == 'bzz') {
                data.feed = (await FeedMapper.selectFeedById(Number.parseInt(prop.id), 'Bzz') as Feed[])[0]
                targetType = TargetType.BZZ
            }
            deptList.value = (await DeptMapper.selectDept() as Dept[])
            roomList.value = await RoomMapper.selectRoomList() as Room[]
            data.feed.deptName = deptList.value.filter(it=>it.deptId == data.feed.deptId)[0].deptName
            data.feed.roomName = roomList.value.filter(it=>it.id == data.feed.roomId)[0].roomName
        }
    })

    const changeDepts = computed(() => {
        return deptList.value?.map(it=>{
            return {text:it.deptName,value:it.deptId}
        })
    })

    const changeRooms = computed(() => {
        return roomList.value.filter(it => it.deptId == feed.value.changeDeptId).map(it=>{
            return {text:it.roomName,value:it.id}
        })
    })

    const glChangeRooms = computed(() => {
        return roomList.value.filter(it => it.deptId == feed.value.glChangeDeptId).map(it=>{
            return {text:it.roomName,value:it.id}
        })
    })

    const handleConfrim = (type: '0' | '2') => {
        tableStatus.value = type
        title.value = `是否${type == '2' ? '拒绝' : '同意'}批号为：‘${feed.value?.batchNumber}’的数据项`
        isShow.value.open()
    }

    const submit = () => {
        FeedMapper.updateFeedById({
            tableStatus:tableStatus.value as string,
            remark:remark.value,
            id:feed.value.id
        } as Feed, role == 'head' ? 'Head' : 'Bzz')
            .then(() => {
                LocalChangeMapper.selectLocalChangeByTargetId(feed.value.id+'',targetType).then(res=>{
                    // @ts-ignore
                    if (res.length == 0){
                        LocalChangeMapper.insertLocalChange({
                            targetId: feed.value?.id + '',
                            targetType: targetType,
                            changeStatus: ChangeStatus.UNSYNC,
                            changeType: ChangeType.upd,
                            userId: store.getters.userId,
                            changeTime: parseTime(new Date(), null)
                        } as LocalChange).then(() => {
                            uni.navigateBack()
                        })
                    }else {
                        uni.navigateBack()
                    }
                })
            }).catch(() => {
                uni.showToast({
                    title:'提交失败',
                    icon:'error'
                })
            })
    }

    return {
        title,
        isShow,
        handleConfrim,
        submit,
        remark,
        feed,
        changeRooms,
        changeDepts,
        glChangeRooms
    }
}
